package com.example.gateway.security.authorization;


import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class CustomAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {

        log.info("[CustomAuthorizationManager] check: {} - {}", authentication, authorizationContext);
        return Mono.just(new AuthorizationDecision(true));
        // authentication 为空时，会直接走到defaultIfEmpty，而不会走map方法
//        return authentication
//                .map(auth -> checkAuthorities(auth, authorizationContext.getExchange()))
//                .map(AuthorizationDecision::new)
//                .defaultIfEmpty(new AuthorizationDecision(false));
    }


    private boolean checkAuthorities(Authentication auth, ServerWebExchange exchange) {
        log.info("[CustomAuthorizationManager] checkAuthorities: {} - {}", auth.getName(), auth.getPrincipal());
        return true;
    }
}
